package com.xatz.scanner

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.symbol.emdk.barcode.ScannerException
import com.xatz.scanner.databinding.ActivityBarcodeQueryBinding
import timber.log.Timber

/**
 * author: tdq
 * date: 2021/7/21
 * description: 条码查询
 */
class BarcodeQueryActivity : AppCompatActivity(),
    ScannerManger.OnScannerResultListener {

    private lateinit var mBinding: ActivityBarcodeQueryBinding

    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityBarcodeQueryBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        ScannerManger.init(this)
        ScannerManger.setOnScannerResultListener(this)
        mBinding.btnScan.setOnClickListener {
            ScannerManger.bSoftTriggerSelected = true
            if (ScannerManger.scanner != null) {
                if (ScannerManger.scanner?.isReadPending == true) {
                    try {
                        ScannerManger.scanner?.cancelRead()
                    } catch (e: ScannerException) {
                        Timber.e(e)
                    }
                }
            }
        }

        mBinding.webView.settings.javaScriptEnabled = true
    }

    override fun onScannerResult(data: String?, labelType: String) {
        runOnUiThread {
            if (labelType == "QRCODE") {
                data?.let { mBinding.webView.loadUrl(it) }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ScannerManger.onClosed()
    }

    override fun onResume() {
        super.onResume()
        // The application is in foreground
        if (ScannerManger.emdkManager != null) {
            // Acquire the barcode manager resources
            ScannerManger.initBarcodeManager(this)
        }
    }

    override fun onPause() {
        super.onPause()
        // The application is in background
        // Release the barcode manager resources
        ScannerManger.deInitScanner()
        ScannerManger.deInitBarcodeManager()
    }
}